package com.atguigu.gulimall.member.controller;

import com.atguigu.common.exception.BizCodeException;
import com.atguigu.common.exception.RRException;
import com.atguigu.common.to.MemberTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import com.atguigu.gulimall.member.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;


/**
 * 会员
 *
 * @author DoGH
 * @since 2024-08-22 10:55:10
 */
@RestController
@RequestMapping("member/member")
public class MemberController {
    @Autowired
    private MemberService memberService;

    /**
     * 注册会员
     *
     * @param memberVO 会员
     * @return {@link R }
     * @author DuGuanghan
     * @since 2024-08-22 16:30:31
     */
    @PostMapping("/regist")
    public R regist(@RequestBody MemberVO memberVO) {
        try {
            memberService.regist(memberVO);
        } catch (RRException e) {
            return R.error(e.getCode(), e.getMsg());
        }

        return R.ok();
    }

    @PostMapping("/login")
    public R login(@RequestBody MemberVO memberVO) {
        MemberTo member = memberService.login(memberVO);

        if (member != null) {
            R r = R.ok();
            r.setData(member);
            return r;
        } else {
            return R.error(BizCodeException.LOGIN_ERROR_EXCEPTION.getCode(), BizCodeException.LOGIN_ERROR_EXCEPTION.getMsg());
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = memberService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		MemberEntity member = memberService.getById(id);

        return R.ok().put("member", member);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody MemberEntity member){
		memberService.save(member);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody MemberEntity member){
		memberService.updateById(member);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		memberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
